# -*- coding: utf-8 -*-
from datetime import datetime
from abc import ABC
from tornado.gen import coroutine

import app.models.dao as dao
import app.tools.sm_config_reader as layer_type
from app.views import SmBaseHandler, CommonHandler
from app.models.dao import db2vectors, delete, add, db2meta, update
from app.models.model import SMVentilateModel, MetaModel


# kj83里面 m_position表格中的 layer字段对应值的字典
LayerType = layer_type.LayerType
mine_id = layer_type.default_MineId
meta_id = layer_type.default_MetaId


class VentilationHandler(SmBaseHandler, ABC):
    @coroutine
    def get(self):
        data = yield dao.get_ventilation()
        self.finish({'data': data})


class VentilationRotationHandler(CommonHandler, ABC):
    async def get(self):
        mid = self.get_argument("meta_id", None)
        ventilation = db2vectors(SMVentilateModel, mid)
        await self.response(data=ventilation)

    async def post(self):
        params = self.json_params()
        ventilation = SMVentilateModel(params)
        add(ventilation)

        # 删除之后，需要返回客户端的剩余风向线
        ventilation = db2vectors(SMVentilateModel, meta_id)

        # 修改后, 修改数据库中图纸的版本, 方便其他客户端进行数据更新,将meta版本 + 1
        meta = db2meta(meta_id)
        mid = meta['id']
        version_num = meta['mine_name'][1:]
        meta['mine_name'] = 'v' + str(int(version_num) + 1)

        # 时间也需要做更新
        meta['update_time'] = datetime.now()
        meta['create_time'] = datetime.fromisoformat(meta['create_time'])
        update(MetaModel, mid, meta)

        # 再获取一遍最新的meta信息
        current_meta = db2meta(meta_id)
        await self.response(data={
            'type': 'success',
            'data': ventilation,
            'meta': current_meta
        })

    async def delete(self):
        params = self.json_params()
        print('ventilate delete param',params)
        mid = params['node_id']
        delete(SMVentilateModel, mid)

        # 删除之后，需要返回客户端的剩余风向线
        ventilation = db2vectors(SMVentilateModel, meta_id)

        # 修改完成后 同时修改数据库中图纸的版本，方便其他客户端进行数据更新  将meta版本 + 1
        meta = db2meta(meta_id)
        mid = meta['id']
        version_num = meta['mine_name'][1:]
        meta['mine_name'] = 'v' + str(int(version_num) + 1)

        # 时间也需要做更新
        meta['update_time'] = datetime.now()
        meta['create_time'] = datetime.fromisoformat(meta['create_time'])
        update(MetaModel, mid, meta)

        # 再获取一遍最新的meta信息
        current_meta = db2meta(meta_id)
        await self.response(data={
            'type': 'success',
            'data': ventilation,
            'meta': current_meta
        })
